package git.soulbgm.service.impl;
import java.util.Date;

import com.baomidou.dynamic.datasource.annotation.DS;
import git.soulbgm.common.base.BaseServiceImpl;
import git.soulbgm.pojo.OrderDto;
import git.soulbgm.service.AccountService;
import git.soulbgm.service.GoodsService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import git.soulbgm.pojo.Orders;
import git.soulbgm.service.OrderService;
import git.soulbgm.mapper.OrderMapper;

/**
 * 订单表
 *
 * @author SoulBGM
 * @version V1.0
 * @date 2020-11-06 17:27:16
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private AccountService accountService;

    @DS("order-ds")
    @GlobalTransactional
    @Override
    public Long createOrder(OrderDto dto) throws Exception {
        // 扣减库存
        goodsService.reduceInventory(dto.getGoodsId(), dto.getAmount());
        // 扣减余额
        accountService.reduceBalance(dto.getAccountId(), dto.getPrice());
        // 保存订单
        Orders orders = new Orders();
        orders.setAccountId(dto.getAccountId());
        orders.setGoodsId(dto.getGoodsId());
        orders.setPayAmount(dto.getPrice());
        orders.setCreateTime(new Date());
        orders.setStatus(0);
        boolean result = save(orders);
        // 返回订单编号
        if (result) {
            return orders.getId();
        }
        return 0L;
    }

}